package cn.itcast.web.controller.cargo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.domain.cargo.Goods;
import cn.itcast.domain.cargo.GoodsExample;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.service.cargo.GoodsService;
import cn.itcast.util.DownloadUtils;
import cn.itcast.util.ImageUploadUtils;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/cargo/goods", name = "产品模块")
public class GoodsController extends BaseController {
    @Reference
    private GoodsService goodsService;
    @Reference
    private FactoryService factoryService;

    @RequestMapping(value = "/list", name = "产品信息查询")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        GoodsExample goodsExample = new GoodsExample();
        PageInfo page = goodsService.findByPage(pageNum, pageSize, goodsExample);
        request.setAttribute("page", page);

        return "cargo/goods/goods-list";
    }

    @RequestMapping(value = "/toAdd", name = "新建")
    public String toAdd() {
        FactoryExample factoryExample = new FactoryExample();
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);
        return "cargo/goods/goods-add";
    }


    @RequestMapping(value = "/edit", name = "新增或修改")
    public String edit(Goods goods, MultipartFile productPhoto)throws Exception {


        // 非空判断
        if(productPhoto!=null && !productPhoto.isEmpty()){
            // 调用七牛云工具类实现文件上传
            String imgUrl = ImageUploadUtils.upload(productPhoto.getInputStream());
            goods.setProductImage(imgUrl);
        }


        if (StrUtil.hasEmpty(goods.getId())) {
            goods.setCreateTime(new Date());
            goods.setCreateBy(getLoginUser().getId());
            goods.setCreateDept(getLoginUser().getDeptId());
            goods.setInputTime(new Date());
            goodsService.save(goods);
        } else {
            goods.setInputTime(new Date());
            goodsService.update(goods);
        }

        return "redirect:/cargo/goods/list.do";
    }
    @RequestMapping(value = "/toUpdate",name = "修改")
    public String toUpdate(String id){
        Goods goods = goodsService.findById(id);
        request.setAttribute("goods",goods);

        FactoryExample factoryExample = new FactoryExample();
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);
        return "cargo/goods/goods-update";
    }
    @RequestMapping(value = "/delete",name = "删除")
    public String delete(String id){
        goodsService.delete(id);
        return "redirect:/cargo/goods/list.do";
    }
    @RequestMapping("/goodsPdf")
    public void goodsPdf(String id) throws Exception {
        // 1.加载模板
        String realPath = request.getSession().getServletContext().getRealPath("/jasper/demo4.jasper");
        // 2.填充数据
    /*
            参数一：模板路径
            参数二：map集合类型数据
            参数三：list集合类型数据（JRDataSource）
         */

        // 2.1查询报运单对象转为map集合
        Factory factory = factoryService.findById(id);
        // hutool工具包，可以将对象转为map集合，key=对象属性名，value=对象属性值
        Map<String, Object> map = BeanUtil.beanToMap(factory);

        // 2.2查询报运单商品列表转为JRDataSource
        GoodsExample goodsExample = new GoodsExample();
        List<Goods> goodsList = goodsService.findAll(goodsExample);
        JRBeanCollectionDataSource jrDataSource = new JRBeanCollectionDataSource(goodsList);

        JasperPrint jasperPrint = JasperFillManager.fillReport(realPath, map, jrDataSource);

        //  3.生成PDF输出到客户端
        //JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
        // 4.pdf文件下载
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 创建字节数组输出流
        JasperExportManager.exportReportToPdfStream(jasperPrint, byteArrayOutputStream); // 将pdf输出到字节数组输出流中
        DownloadUtils.download(byteArrayOutputStream, response, "产品介绍单.pdf");// 完成文件下载
    }
}